<?php
/**
 * Author Yulin
 * Email  dwzhanglong@126.com
 * Date   2017-6-3
 * Func   注册会员
 */
defined('IN_YuLin') || exit('NO PERMIT!');

$table = Table('user');
$utable = Table('user_info');
$stable = Table('user_status');
$ltable = Table('user_infolog');

$gids = [1=>'普通用户','代理'];

if(IS_POST)
{
	$id = intval($_POST['id']);
	$sql = "select id from ".$table." where id = ".$id;
	$res = $db->getrow($sql);
	!$res && ShowMsg('操作失败',U($m."/".$c));

	if($a == "edit_info"){
		$data['nickname'] 		= trim(NoBadStr($_POST['nickname']));
		$data['mobile'] 		= trim(NoBadStr($_POST['mobile']));
		$data['truename'] 		= trim(NoBadStr($_POST['truename']));
		$data['email'] 			= trim(NoBadStr($_POST['email']));
		$data['qq'] 			= trim(NoBadStr($_POST['qq']));
		$data['wechat'] 		= trim(NoBadStr($_POST['wechat']));
		// 更新基本信息
		$db->exec("UPDATE ".$utable." SET ".CreateUpdateSql($data)." WHERE uid = ".$id);

		// 更新密码
		$password 				= trim(NoBadStr($_POST['password']));
		$paypassword 			= trim(NoBadStr($_POST['paypassword']));
		!empty($password) && $data2['password'] = Password($password);
		!empty($paypassword) && $data2['paypassword'] = Password($paypassword);
		!empty($data2) && $db->exec("UPDATE ".$table." SET ".CreateUpdateSql($data2)." WHERE id = ".$id);

		// 更新日志
		$logoData['aid'] = $_uid;
		$logoData['uid'] = $id;
		$logoData['tid'] = 0;
		$tmp  = "昵称:".$data['nickname'];
		$tmp .= "，手机:".$data['mobile'];
		$tmp .= "，姓名:".$data['truename'];
		$tmp .= "，邮箱:".$data['email'];
		$tmp .= "，QQ:".$data['qq'];
		$tmp .= "，微信:".$data['wechat'];
		$tmp .= "，登录密码:".$password;
		$tmp .= "，支付密码:".$paypassword;
		$logoData['content'] = $tmp;
		$logoData['dateline'] = time();
		$logoData['ip'] = GetIp();
		$db->exec("INSERT INTO ".$ltable.CreateInsertSql($logoData));
		ShowMsg('操作成功',U($m."/".$c));
	}else if($a == 'recharge'){
		$data['money'] = floatval($_POST['money']);
		$remark = trim(NoBadStr($_POST['remark']));
		$remark = !empty($remark) ? $remark : "用户后台充值";
		($data['money'] < 0) && ShowMsg('操作失败!',U($m."/".$c));
		$data['uid'] = $id;
		$data['balance'] = $data['money'];
		$data['tid'] = 'recharge';
		$data['lkey'] = 'CZ'.$id.date('_YmdHis_').rand(1000,9999);
		$data['notes'] = $remark;
		$result = MoneyLog($data);
		rechargeCheckLevel(array('uid' => $id, 'recharge_money' => $data['money']));
		ShowMsg('操作成功',U($m."/".$c));
	}else{
	    $data = $id ? $db->getrow('SELECT * FROM '.$table.' WHERE id = '.$id) : [];
	    
	    $ins = [];
		$ins['gid']	=	intval($_POST['gid']);
	    $password = trim($_POST['password']);
		$password && $ins['password'] = Password($password);
	    $paypassword = trim($_POST['paypassword']);
		$paypassword && $ins['paypassword'] = Password($paypassword);
		
		$ins2 = [];
		$ins2['nickname']	=	NoBadStr($_POST['nickname']);
		$ins2['truename']	=	NoBadStr($_POST['truename']);
		$ins2['email']		=	NoBadStr($_POST['email']);
		$ins2['mobile']		=	NoBadStr($_POST['mobile']);
		$ins2['qq']			=	NoBadStr($_POST['qq']);
		$ins2['wechat']		=	NoBadStr($_POST['wechat']);
		
		$ins3 = [];
		$ins3['invest']		=	intval($_POST['invest']);
		$ins3['profit']		=	intval($_POST['profit']);
		$ins3['rebate']		=	round($_POST['rebate'],2);
	    
	    if($data['id'])
	    {
	        $msg = '修改会员成功';
	        $db->exec('UPDATE '.$table.' SET '.CreateUpdateSql($ins).' WHERE id = '.$data['id']);
			
			//	附表
			$db->exec('UPDATE '.$utable.' SET '.CreateUpdateSql($ins2).' WHERE uid = '.$data['id']);
			
			//	状态表
			$db->exec('UPDATE '.$stable.' SET '.CreateUpdateSql($ins3).' WHERE uid = '.$data['id']);
			
			//	修改记录
			$tmp = '昵称：'.$ins2['nickname'];
			$tmp.= '，手机：'.$ins2['mobile'];
			$tmp.= '，姓名：'.$ins2['truename'];
			$tmp.= '，邮箱：'.$ins2['email'];
			$tmp.= '，QQ：'.$ins2['qq'];
			$tmp.= '，微信：'.$ins2['wechat'];
			$tmp.= '，登录密码：'.$password;
			$tmp.= '，支付密码：'.$paypassword;
			$tmp.= '，会员类型：'.$gids[$ins['gid']];
			$tmp.= '，投注功能：'.($ins3['invest'] ? '是' : '否');
			$tmp.= '，返点比例：'.($ins3['profit'] ? '是' : '否');
			$tmp.= '，代理返点：'.$ins3['rebate'];
			$t2 = [];
			$t2['aid']		=	$_uid;
			$t2['uid']		=	$data['id'];
			$t2['tid']		=	0;
			$t2['content']	=	$tmp;
			$t2['dateline']	=	TIMESTAMP;
			$t2['ip']		=	$_Y['ip'];
			$db->exec('INSERT INTO '.$ltable.CreateInsertSql($t2));
	    }
	    /*else
	    {
	        $ins['status']      =   1;
	        $ins['dateline']    =   TIMESTAMP;
	        
	        $msg = '添加公司成功';
	        $db->exec('INSERT INTO '.$table.CreateInsertSql($ins));
	        
	        $data['id'] = $db->insert_id();
	        !$data['id'] && AjaxReturn(1,'添加公司失败');
			
			//	附表
			$ins2['uid'] = $data['id'];
	        $db->exec('INSERT INTO '.$utable.CreateInsertSql($ins2));
	    }*/
	    
		AjaxReturn(0,$msg);		
	}
    
}
	
if($a == 'add')
{
    $id = intval($_GET['id']);
    !$id && ShowMsg('编辑失败！',U($m."/".$c));
    $data = $db->getrow('SELECT t.*,u.*,s.* FROM '.$table.' t LEFT JOIN '.$utable.' u ON t.id = u.uid LEFT JOIN '.$stable.' s ON t.id = s.uid WHERE t.id = '.$id);
    
    $tpl->display('user/index_add');
}
else if($a == 'view')
{
	$id = intval($_GET['uid']);
    $data = $db->getrow('SELECT t.*,u.*,s.* FROM '.$table.' t LEFT JOIN '.$utable.' u ON t.id = u.uid LEFT JOIN '.$stable.' s ON t.id = s.uid WHERE t.id = '.$id);
    
	//	上级
	$data['upname'] = '';
	if($data['upuid'])
	{
		$tmp = $db->getrow('SELECT username FROM '.$table.' WHERE id = '.$id);
		$data['upname'] = $tmp['username'];
	}
	
	//	存款次数和金额
	$recharge = $db->getrow('SELECT SUM(money) AS money,COUNT(1) AS p FROM '.Table('user_money_recharge').' WHERE uid = '.$id.' AND status = 1');
    
	//	提款次数和金额
	$cash = $db->getrow('SELECT SUM(money) AS money,COUNT(1) AS p FROM '.Table('user_money_cash').' WHERE uid = '.$id.' AND status = 1');
	
    $tpl->display('user/index_view');
}
else if($a == 'del')
{
    $id = trim($_GET['id']);
    if($id)
    {
        $id = explode(',',$id);
        foreach($id as $key => $val)
        {
			$id[$key] = intval($val);
        }
		
        $flag = $_GET['flag'] ? 1 : 0;
        $db->exec('UPDATE '.$table.' SET status = '.$flag.' WHERE id IN ('.implode(',',$id).')');
		
		//	修改记录
		$tmp = [];
		$flag = $flag ? '启用' : '禁用';
		foreach($id as $val)
		{
			$tmp[] = '('.$_uid.','.$val.',1,\''.$flag.'\','.TIMESTAMP.',\''.$_Y['ip'].'\')';
		}
		$db->exec('INSERT INTO '.$ltable.'(aid,uid,tid,content,dateline,ip) VALUES '.implode(',',$tmp));
		
		//ShowMsg('操作成功','?m='.$m.'&c='.$c);
        //AjaxReturn(['error'=>'0','msg'=>'操作成功']);
    }
	
	//ShowMsg('操作成功','?m='.$m.'&c='.$c);
	AjaxReturn(['error'=>'1','msg'=>'参数错误']);
}
else if($a == 'infolog')	//	记录
{
	$itids = ['修改资料','修改状态'];
	$uid = intval($_GET['uid']);
	
	$data = $db->getall('SELECT t.*,u.username,a.username AS aname FROM '.$ltable.' t LEFT JOIN '.$table.' u ON t.uid = u.id LEFT JOIN '.Table('admin_user').' a ON t.aid = a.id WHERE t.uid = '.$uid.' ORDER BY t.id DESC');
	
	$tpl->display('user/index_infolog');
}
else
{
	$statuss = ['禁用','启用'];
	$orderbys = ['dtdesc'=>'注册时间倒序','dtasc'=>'注册时间升序','rebatedesc'=>'返点倒序','rebateasc'=>'返点升序','moneydesc'=>'余额倒序','moneyasc'=>'余额升序'];
	$orderbys2 = ['dtdesc'=>'t.id DESC','dtasc'=>'t.id','rebatedesc'=>'s.rebate DESC','rebateasc'=>'s.rebate','moneydesc'=>'t.money DESC','moneyasc'=>'t.money'];
	
	$data  = array();
	$where = ' FROM '.$table.' t LEFT JOIN '.$utable.' u ON t.id = u.uid LEFT JOIN '.$stable.' s ON t.id = s.uid WHERE 1 ';
    
	$upuid = intval($_GET['upuid']);
	$upuid && $where .= ' AND s.upuid = '.$upuid;
	
	$gid = intval($_GET['gid']);
	$gid && $where .= ' AND t.gid = '.$gid;
	
    $status = intval($_GET['status']);
	$status && $where .= ' AND t.status = '.($status > 0 ? $status : 0);
	
	//	时间
	$dt1 = NoBadStr($_GET['dt1']);
	$dt1 && $where .= ' AND t.reg_time >= '.strtotime($dt1);
	$dt2 = NoBadStr($_GET['dt2']);
	$dt2 && $where .= ' AND t.reg_time <= '.strtotime($dt2);
    
	$title = NoBadStr($_GET['title']);
	$title && $where .= ' AND (t.username LIKE \'%'.$title.'%\' OR u.nickname LIKE \''.$title.'\') ';
	
	//	排序
	$orderby = NoBadStr($_GET['orderby']);
	!array_key_exists($orderby,$orderbys) && $orderby = 'dtdesc';

	$tmp = $db->getrow('SELECT COUNT(1) AS p '.$where);
	if($tmp['p'])
	{
		$page = max(1,intval($_GET['page']));
		$size = 20;
		$limit = $_GET['export'] ? '' : ' LIMIT '.($page - 1) * $size.','.$size;
		
		$url = '?m='.$m.'&c='.$c.'&a='.$a.'&title='.$title.'&status='.$status.'&upuid='.$upuid.'&gid='.$gid.'&dt1='.$dt1.'&dt2='.$dt2.'&orderby='.$orderby;
		
		$data = $db->getall('SELECT t.*,u.*,s.* '.$where.' ORDER BY '.$orderbys2[$orderby].$limit);
		
		//	上级用户
		$upuids = [];
		foreach($data as $key => $val)
		{
			$val['upuid'] && $upuids[$val['upuid']] = '';
		}
		$upuids && $upuids = $db->getall('SELECT id,username FROM '.$table.' WHERE id IN ('.implode(',',array_keys($upuids)).')','id');
		
		$multi = Multi($url,$page,$tmp['p'],$size);
	}
	
	//	导出
	if($_GET['export'])
	{
		header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=".'会员列表'.date("YmdHis").".xls"); //“生成文件名称”=自定义
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');

		echo "上级\t账户\t昵称\t会员类型\t余额\t返点\t注册日期\t注册IP\t最后登陆IP\t下级人数\t状态\t推广码\t\n";
        foreach ($data as $key => $val)
        {
			echo $upuids[$val['upuid']]['username'],"\t";
			echo $val['username'],"\t";
			echo $val['nickname'],"\t";
			echo $gids[$val['gid']],"\t";
			echo $val['money'],"\t";
			echo $val['rebate'],"%\t";
			echo date('Y/m/d H:i',$val['reg_time']),"\t";
			echo $val['reg_ip'],"\t";
			echo $val['last_ip'],"\t";
			echo $val['sons'],"\t";
			echo $statuss[$val['status']],"\t";
			echo $val['id'],"\t";"\t\n";
        }
		exit;
	}
	
	//	所有用户
	$agents = $db->getall('SELECT t.id,t.username,s.sons FROM '.$table.' t LEFT JOIN '.$stable.' s ON t.id = s.uid WHERE t.gid = 2 ORDER BY s.sons DESC');
	
	$tpl->display('user/index');
}